package com.burningtower.service.impl;

import com.burningtower.common.Result;
import com.burningtower.entity.Category;
import com.burningtower.repo.CategoryRepository;
import com.burningtower.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/11/6.
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryRepository categoryRepository;
    /**
     * 获取品类子节点(平级)
     * @param categoryId
     * @return Result<List<Category>>
     */
    @Override
    public Result<List<Category>> getListById(Integer categoryId) {
        Category category=new Category();
        category.setParentId(categoryId);
        List<Category> list = categoryRepository.findAll(Example.of(category));
        if(list==null){
            throw new RuntimeException("未找到该品类");
        }
        Result<List<Category>> result = new Result<>();
        result.setData(list);
        result.setStatus(0);
        return result;
    }

    /**
     * 增加节点
     * @param parentId
     * @param categoryName
     * @return Result<String>
     */
    @Override
    public Result<String> add(Integer parentId,String categoryName) {
        Category category = new Category();
        category.setParentId(parentId);
        category.setName(categoryName);
        category.setCreateTime(new Date());
        categoryRepository.save(category);
        Result<String> result = new Result<>();
        result.setMsg("添加品类成功");
        result.setStatus(0);
        return result;
    }

    /**
     * 修改品类名字
     * @param categoryId
     * @param categoryName
     * @return Result<String>
     */
    @Override
    public Result<String> update(Integer categoryId, String categoryName) {
        Category category = categoryRepository.findOne(categoryId);
        category.setName(categoryName);
        category.setUpdateTime(new Date());
        categoryRepository.save(category);
        Result<String> result = new Result<>();
        result.setMsg("更新品类名字成功");
        result.setStatus(0);
        return result;
    }

    /**
     * 获取当前分类id及递归子节点categoryId
     * @param categoryId
     * @return Result<Integer[]>
     */
    @Override
    public Result<Integer[]> getDeepById(Integer categoryId) {
        Category category = new Category();
        category.setParentId(categoryId);
        List<Category> list = categoryRepository.findAll(Example.of(category));
        Integer [] a=new Integer[list.size()];
        for(int i=0;i<list.size();i++){
            a[i]=list.get(i).getId();
        }
        Result<Integer[]> result= new Result<>();
        result.setData(a);
        result.setStatus(0);
        return result;
    }
}
